package com.glenet.salary.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;

import com.glenet.salary.entities.HrEmployee;
import com.glenet.salary.util.SessionFactoryUtil;

public class HrEmployeeDao extends HrDaoSuport {

	public boolean save(HrEmployee employee) {
		boolean flag = false;
		try {
			SqlSession session = SessionFactoryUtil.openSession();
			flag = session.insert("HrEmployee.save", employee) > 0 ? true : false;
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	public int batchSave(List<HrEmployee> list){
		int effect = 0;
		try {
			SqlSession session = SessionFactoryUtil.getSessionFactory().openSession(ExecutorType.BATCH);
			for (HrEmployee hrEmployee : list) {
				effect = +session.insert("HrEmployee.save", hrEmployee);
			}
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(effect);
		return effect;
	}
	
	public boolean update(HrEmployee employee) {
		boolean flag = false;
		try {
			SqlSession session = SessionFactoryUtil.openSession();
			flag = session.update("HrEmployee.update", employee) > 0 ? true : false;
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	public boolean delete(Long id) {
		boolean flag = false;
		try {
			SqlSession session = SessionFactoryUtil.openSession();
			flag = session.update("HrEmployee.delete", id) > 0 ? true : false;
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	public List<HrEmployee> list(int offset, int limit) {
		List<HrEmployee> list = new ArrayList<HrEmployee>(0);
		try {
			SqlSession session = SessionFactoryUtil.openSession();
			list = session.selectList("HrEmployee.list", null, new RowBounds(offset, limit));
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public HrEmployee get(Long id) {
		HrEmployee emp = new HrEmployee();
		try {
			SqlSession session = SessionFactoryUtil.openSession();
			emp = (HrEmployee) session.selectOne("HrEmployee.get", id);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return emp;
	}

	public Long getEmployeeId(String name, String idcard) {
		Long eid = null;
		try {
			SqlSession session = SessionFactoryUtil.openSession();
			Map<String, String> map = new HashMap<String, String>();
			map.put("name", name);
			map.put("idcard", idcard);
			eid = (Long) session.selectOne("HrEmployee.getEmployeeId", map);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return eid;
	}
}
